﻿using Microsoft.AspNetCore.Mvc;
using SMARTHOTEL.hotel;
using SMARTHOTEL.Products;
using SMARTHOTEL.pudlic;
using SMARTHOTEL.RoomStatues;
using SMARTHOTEL.RoomTypes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace SMARTHOTEL.RoomConditionManagement
{

    /// <summary>
    /// 房态管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "v2")]
    public class RoomCondition : ApplicationService, IRoomCondition
    {
        /// <summary>
        /// 房间类型
        /// </summary>
        private readonly IRepository<RoomType> RoomTypeRepository;
        /// <summary>
        /// 房间号
        /// </summary>
        private readonly IRepository<RoomNumber> RoomNumberRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roomTypeRepository">房间类型</param>
        ///  /// <param name="roomNumberRepository">房间号</param>
        public RoomCondition(IRepository<RoomType> roomTypeRepository, IRepository<RoomNumber> roomNumberRepository)
        {
            RoomTypeRepository = roomTypeRepository;
            RoomNumberRepository = roomNumberRepository;
        }


        /// <summary>
        /// 获取房间类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRCRoomType")]
        public async Task<ResultDto<List<RCRoomTypeDto>>> GetRCRoomType()
        {
            try
            {

                // 获取房型列表
                var roomTypesQuery = await RoomTypeRepository.GetQueryableAsync();

                // 获取房号列表
                var roomNumbersQuery = await RoomNumberRepository.GetQueryableAsync();

                // 左连接并分组统计（EF Core 可翻译的写法）
                var query =
                    from rt in roomTypesQuery
                    join rn in roomNumbersQuery
                        on rt.Id equals rn.RoomTypeId into rnGroup
                    from subRn in rnGroup.DefaultIfEmpty() // 左连接关键步骤
                    group subRn by new { rt.Id, rt.RoomTypeName } into g
                    select new RCRoomTypeDto
                    {
                        value = g.Key.Id,
                        label = g.Key.RoomTypeName,
                        count = g.Count(rn => rn != null) // 统计有效房号数量
                    };

                //返回
                return new ResultDto<List<RCRoomTypeDto>> { Code = StatusCode.Success, Data = query.ToList(), Message = "获取房间类型成功" };


            }
            catch (Exception ex)
            {
                //返回
                return new ResultDto<List<RCRoomTypeDto>> { Code = StatusCode.Faield, Message = "获取房间类型失败" + " " + ex.Message };

            }
        }

        /// <summary>
        /// 获取额外房间状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetExtrRCRoomState")]
        public async Task<ResultDto<List<RCExtraRoomStateDto>>> GetExtrRCRoomState()
        {
            try
            {
                var query = await RoomNumberRepository.GetQueryableAsync();

                // 1. 获取分组结果列表
                var groupedResults = query
                    .GroupBy(r => r.RoomNumberExtraStatues)
                    .Select(g => new
                    {
                        State = g.Key,
                        Count = g.Count()
                    })
                    .ToList(); // ✅ 直接获取分组列表

                // 2. 获取带描述的枚举列表
                var enumList = Enum.GetValues(typeof(ManyState)) // 根据实际枚举类型调整
                    .Cast<ManyState>()
                    .Select(e => new
                    {
                        Value = (int)e,
                        Name = e.ToString(),
                        Description = e.GetDescription()
                    })
                    .ToList();

                // 3. 直接遍历枚举并匹配数量
                var list = enumList.Select(e =>
                {
                    // 在分组结果中查找匹配项
                    var matchedGroup = groupedResults
                        .FirstOrDefault(g => (int)g.State == e.Value);

                    return new RCExtraRoomStateDto
                    {
                        value = e.Description,
                        label = e.Name,
                        count = matchedGroup?.Count ?? 0 // 无匹配时返回0
                    };
                }).ToList();

                return new ResultDto<List<RCExtraRoomStateDto>>
                {
                    Code = StatusCode.Success,
                    Data = list,
                    Message = "获取房间状态成功"
                };
            }
            catch (Exception ex)
            {
                return new ResultDto<List<RCExtraRoomStateDto>>
                {
                    Code = StatusCode.Faield, // 修正拼写错误
                    Message = $"获取房间状态失败: {ex.Message}"
                };
            }
        }
        /// <summary>
        /// 获取房间状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRCRoomState")]
        public async Task<ResultDto<List<RCRoomStateDto>>> GetRCRoomState()
        {
            try
            {
                var query = await RoomNumberRepository.GetQueryableAsync();

                // 1. 获取分组结果列表
                var groupedResults = query
                    .GroupBy(r => r.RoomNumberNewStatues)
                    .Select(g => new
                    {
                        State = g.Key,
                        Count = g.Count()
                    })
                    .ToList(); // ✅ 直接获取分组列表

                // 2. 获取带描述的枚举列表
                var enumList = Enum.GetValues(typeof(RoomStatue)) // 根据实际枚举类型调整
                    .Cast<RoomStatue>()
                    .Select(e => new
                    {
                        Value = (int)e,
                        Name = e.ToString(),
                        Description = e.GetDescription()
                    })
                    .ToList();

                // 3. 直接遍历枚举并匹配数量
                var list = enumList.Select(e =>
                {
                    // 在分组结果中查找匹配项
                    var matchedGroup = groupedResults
                        .FirstOrDefault(g => (int)g.State == e.Value);

                    return new RCRoomStateDto
                    {
                        value = e.Description,
                        label = e.Name,
                        count = matchedGroup?.Count ?? 0 // 无匹配时返回0
                    };
                }).ToList();

                return new ResultDto<List<RCRoomStateDto>>
                {
                    Code = StatusCode.Success,
                    Data = list,
                    Message = "获取房间状态成功"
                };
            }
            catch (Exception ex)
            {
                return new ResultDto<List<RCRoomStateDto>>
                {
                    Code = StatusCode.Faield,
                    Message = $"获取房间状态失败: {ex.Message}"
                };
            }
        }


        /// <summary>
        /// 获取房间号
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRCRoomNnmber")]
        public async Task<ResultDto<List<RCRoomNumberDto>>> GetRCRoomNnmber()
        {
            try
            {
                var query = await RoomNumberRepository.GetQueryableAsync();
                var list = query.Select(r => new RCRoomNumberDto
                {
                    number = r.RoomNum,
                    type = r.RoomTypeId.ToString(),
                    status = r.RoomNumberNewStatues.ToString(),
                    roomType = r.RoomNumberExtraStatues.ToString()
                }).ToList();

                return new ResultDto<List<RCRoomNumberDto>> { Code = StatusCode.Success, Data = list, Message = "获取房间号成功" };
            }
            catch (Exception ex)
            {

                return new ResultDto<List<RCRoomNumberDto>> { Code = StatusCode.Success, Message = "获取房间号失败" + " " + ex.Message };
            }
        }


        /// <summary>
        /// 获取房间类型列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRCRoomTypeList")]
        public async Task<ResultDto<List<RCRoomTypeListDto>>> GetRCRoomTypeList()
        {
            try
            {
                // 获取房型列表
                var roomTypesQuery = await RoomTypeRepository.GetQueryableAsync();

        //        // 获取房号列表
          var roomNumbersQuery = await RoomNumberRepository.GetQueryableAsync();

                // 左连接并分组统计（EF Core 可翻译的写法）
                var query =
                    from rt in roomTypesQuery
                    join rn in roomNumbersQuery
                        on rt.Id equals rn.RoomTypeId into rnGroup
                    from subRn in rnGroup.DefaultIfEmpty() // 左连接关键步骤
                    group subRn by new { rt.Id, rt.RoomTypeName, rt.RoomTypePrice } into g
                    select new RCRoomTypeListDto
                    {
                        Id = g.Key.Id,
                        RoomTypePrice= g.Key.RoomTypePrice,
                        RoomTypeName = g.Key.RoomTypeName,
                        Count = g.Count(rn => rn != null) // 统计有效房号数量
                    };


                return new ResultDto<List<RCRoomTypeListDto>>
                {
                    Code = StatusCode.Success,
                    Data = query.ToList(),
                    Message = "获取房间类型列表成功"
                };
            }
            catch (Exception ex)
            {
                // 记录异常日志（建议添加日志记录）
                // Logger.LogError(ex, "获取房间类型列表失败");
                return new ResultDto<List<RCRoomTypeListDto>>
                {
                    Code = StatusCode.Faield,
                    Message = $"获取房间类型列表失败: {ex.Message}"
                };
            }
        }


        /// <summary>
        /// 获取房间
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRCNewRoomType")]
        public async Task<ResultDto<RCRoomTypeListDto>> GetRCNewRoomType(string  num)
        {
            try
            {
                // 获取房型列表RoomTypeName
                var roomTypesQuery = from a in await RoomNumberRepository.GetQueryableAsync()
                                     join b in await RoomTypeRepository.GetQueryableAsync() on a.RoomTypeId equals b.Id
                                     where a.RoomNum == num
                                     select new RCRoomTypeListDto
                                     {
                                         Id = b.Id,
                                         RoomTypeName = b.RoomTypeName,
                                         RoomTypePrice = b.RoomTypePrice,
                                         NumId = a.Id,
                                         RoomNumName = a.RoomNum,
                                         Count = 1

                                     };


                return new ResultDto<RCRoomTypeListDto>
                {
                    Data = roomTypesQuery.First(),
                    Code = StatusCode.Success,
                    Message = $"获取房间类型列表成功"
                };

            }
            catch (Exception ex)
            {
                // 记录异常日志（建议添加日志记录）
                // Logger.LogError(ex, "获取房间类型列表失败");
                return new ResultDto<RCRoomTypeListDto>
                {
                    Code = StatusCode.Faield,
                    Message = $"获取房间类型列表失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取证件
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetIDType")]
        public async Task<ResultDto<List<IDTypeDto>>> GetIDType()
        {
            try
            {

                // 2. 获取带描述的枚举列表
                var enumList = Enum.GetValues(typeof(IDType)) // 根据实际枚举类型调整
                    .Cast<IDType>()
                    .Select(e => new IDTypeDto
                    {
                        ID = (int)e,
                        Name = e.ToString()
                    })
                    .ToList();
                return new ResultDto<List<IDTypeDto>>
                {
                    Code = StatusCode.Faield,
                    Data = enumList,
                    Message = $"获取证件类型列表成功"
                };

            }
            catch (Exception ex)
            {
                // 记录异常日志（建议添加日志记录）
                // Logger.LogError(ex, "获取房间类型列表失败");
                return new ResultDto<List<IDTypeDto>>
                {
                    Code = StatusCode.Faield,
                    Message = $"获取证件类型列表失败: {ex.Message}"
                };
            }
        }




    }
}
